import { EnumProtocolType } from "../../../../common/protocols/EnumProtocolType";
import { SC_SendHeartBeat } from "../../../../common/protocols/Proto_SendHeartBeat";
import { IMsg } from "../../../../framework/service/Components/WorkOrderInfo";
import { UserEntity } from "./UserEntity";
import _ from "lodash";
export class UserManager {

    private static _instance: UserManager;

    public static get inst(): UserManager {
        if (!this._instance) {
            this._instance = new UserManager();
        }
        return this._instance;
    }

    private _users: { [key: string]: UserEntity } = {};


    public removeUser(userId: string): void {

        if (this._users[userId]) {
            delete this._users[userId];
        }
    }

    public addUser(user: UserEntity): void {
        this._users[user.data.uid] = user;
    }


    public getUser(userId: string): UserEntity {
        return this._users[userId];
    }

    public update(servertime: number): void {

        this.check(servertime);
    }


    public check(servertime:number): void {
        _.each(this._users, user => {
            if (user.isOffline()) {
                //**离线了要做对应的处理 */
                user.kickoff();
                delete this._users[user.data.uid];
                user.update(servertime);
            }
        });
    }


    /**
     * 发送给所有用户
     *
     * @param {IMsg} msg
     * @memberof UserManager
     */
    public sendToAll(msg: IMsg): void {
        _.each(this._users, user => {
            user.send(msg);
        });
    }

    public commingRequest(msg: IMsg, user: UserEntity): void {

        switch (msg.cmdid) {
            case EnumProtocolType.CS_SendHeartBeat: {
                const sc: SC_SendHeartBeat = new SC_SendHeartBeat();
                user.updateOnlineTime();
                user.send(sc);
                break;
            }
            default: {
                break;
            }
        }
    }


}